package com.gxa.company.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.company.dao.CompanyDao;
import com.gxa.company.service.CompanyService;
import com.gxa.company.service.UploadService;
import com.gxa.company.validator.MyValidator;
import dto.ResultDTO;
import entity.Company;
import group.UpdateCompany;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * 公司表(Company)表服务实现类
 *
 * @author makejava
 * @since 2021-05-12 09:22:01
 */
@Service("companyService")
public class CompanyServiceImpl implements CompanyService {
    @Resource
    private CompanyDao companyDao;
    @Autowired
    private MyValidator validator;
    @Autowired
    private UploadService uploadService;


    /**
     * 通过ID查询单条数据
     *
     * @param companyId 主键
     * @return 实例对象
     */
    @Override
    public ResultDTO queryById(Integer companyId) {
        if (companyId==null) {
            return new ResultDTO(1002,"公司ID不能为空！");
        }
        Company company = this.companyDao.queryById(companyId);
        if (company == null) {
            return new ResultDTO(1001,"没有该公司！");
        }
        return new ResultDTO(200,"success",company);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Company> queryAllByLimit(int offset, int limit) {
        return this.companyDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param company 实例对象
     * @return 实例对象
     */
    @Override
    public Company insert(Company company) {
        this.companyDao.insert(company);
        return company;
    }

    /**
     * 修改数据
     *
     * @param company 实例对象
     * @return 实例对象
     */
    @Override
    public ResultDTO update(Company company, MultipartFile file) {
        validator.validate(company, UpdateCompany.class);
        ResultDTO uploadDTO = uploadService.upload(file);
        if (uploadDTO.getCode()!=200) {
            return uploadDTO;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String uploadPath = objectMapper.convertValue(uploadDTO.getData(), String.class);
        company.setCompanyLogo(uploadPath);
        int i = this.companyDao.update(company);
        if (i<1){
            return new ResultDTO(1001,"修改失败！");
        }
        return new ResultDTO(200,"修改成功！");
    }

    /**
     * 通过主键删除数据
     *
     * @param companyId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer companyId) {
        return this.companyDao.deleteById(companyId) > 0;
    }
}
